package com.mashibing.juc.c_026_01_ThreadPool;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * WorkStealingPool底层实现是通过ForkJoinPool实现
 * @author: Yuanzt
 * @Date: 2021/4/2
 */
public class T11_WorkStealingPool {

    public static void main(String[] args) {
        /*每一个线程上面都有单独的队列，ThreadPool是所有线程共享一个任务队列。当一个线程的任务队列执行完成，其他线程的任务队列还在执行，可以*/
        ExecutorService service = Executors.newWorkStealingPool();
        System.out.println(Runtime.getRuntime().availableProcessors());

        service.execute(new R(1000));
        service.execute(new R(2000));
        service.execute(new R(2000));
        service.execute(new R(2000)); //daemon
        service.execute(new R(2000));

        //由于产生的是精灵线程（守护线程、后台线程），主线程不阻塞的话，看不到输出
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    static class R implements Runnable{
        int time;
        R(int t){
            this.time = t;
        }

        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(time + " " + Thread.currentThread().getName());
        }
    }
}
